package com.paic.custserv.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.paic.custserv.common.Constant;
import com.paic.custserv.domain.AppUser;
import com.paic.custserv.utils.CommonUtil;
import com.paic.custserv.vo.SysMenuVO;

public class DefaultUserDetailService{
	
	@Autowired
	private ICussRoleAuthorityService cussRoleAuthorityService;

	public AppUser loadUserByUserrole(String username)
			throws UsernameNotFoundException {
		AppUser appUser = getAppUser(username);
		//角色与资源的映射关系
		appUser.setResourceMap(cussRoleAuthorityService.loadAllResourceMenu());
		return appUser;
	}
	
	/**
     * 查询数据库获取用户信息
     *
     * @param userAccount
     * @return
     */
    private AppUser getAppUser(String userRole) {
    	AppUser appUser = new AppUser();
    	List<SysMenuVO> list = cussRoleAuthorityService.fillMenuInfo(userRole);
    	appUser.setSysMenuList(list);
    	List<SysMenuVO> quickMenuList = new ArrayList<SysMenuVO>();
    	if(!CommonUtil.isNullOrEmpty(list)) {
    		 for(SysMenuVO vo : list) {
    			 if(vo.isHasChild()) {
    				 for(SysMenuVO vo1 : vo.getSubMenuList()) {
    					 if(Constant.ValidFlag.Y.toString().equals(vo1.getIsQuickMenu())) {
    						 quickMenuList.add(vo1);
    					 }
    				 }
    			 }
    		 }
    		 appUser.setQuickMenuList(quickMenuList);
    		 List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    		 setResource(authorities, list);
    		 appUser.setAuthoritys(authorities);
    	}
        return appUser;
    }
    
    private static void setResource(List<GrantedAuthority> authorities, List<SysMenuVO> list) {
    	for(SysMenuVO resource : list) {
			 GrantedAuthority auth = new SimpleGrantedAuthority(String.valueOf(resource.getIdResource()));
			 authorities.add(auth);
			 if(resource.isHasChild()) {
				 setResource(authorities, resource.getSubMenuList());
			 }
		 }
    }
}
